<script setup>
import request from '@/utils/request.js'
import TitleLabel from "@/components/TitleLabel.vue";
import api from '@/api/device.js'

const { proxy } = getCurrentInstance();
const rfidList = ref([]);
const deviceList = ref([]);

const emit = defineEmits(['sub']);

let websocket = null;
let host = window.location.hostname;
let urlPrev = '/rfid/';

function sendCommand(command, data) {
  const message = {
    command: command,
    data: data
  }
  websocket.send(JSON.stringify(message));
}

function createWebsocket(uuid) {
  websocket = new WebSocket(`ws://${host}:8085/rfid`);

  // Set up event listeners
  websocket.onopen = () => {
    console.log('RFID WebSocket connection opened.');
    // 发送uuid的绑定的命令
    sendCommand('setUuid', uuid);
  };

  websocket.onmessage = (event) => {
    const data = event.data;
    const list = rfidList.value;
    if (list.indexOf(data) === -1) {
      list.push(data);
    }
  };

  websocket.onerror = (error) => {
    console.error('WebSocket Error:', error);
  };

  websocket.onclose = () => {
    console.log('WebSocket connection closed.');
  };

  return websocket;
}

function closeWebsocket() {
  if (websocket) {
    websocket.close();
    websocket = null;
  }
}

// 启动RFID的读取
function startInventory(uuid) {
  return request({
    url: `${urlPrev}inventory/${uuid}`,
    method: 'put',
    data: {
      uuid: uuid
    }
  }).then(response => {
    proxy.$modal.msgSuccess("开始RFID读取");
  })
}

// 停止RFID的读取
function stopInventory(uuid) {
  return request({
    url: `${urlPrev}/stopInventory/${uuid}`,
    method: 'put'
  }).then(response => {
    if (!silent) {
      proxy.$modal.msgSuccess("停止RFID读取");
    }
  })
}

function deviceRead(device) {
  const uuid = device.number;
  device.running = true;
  if (!websocket) {
    // 启动websocket监听
    createWebsocket(uuid);
  } else {
    sendCommand('setUuid', uuid);
  }
  // 发送盘点请求
  startInventory(uuid);
}

function deviceStopRead(device) {
  const uuid = device.number;
  device.running = false;
  closeWebsocket();
  // 发送盘点请求
  stopInventory(uuid);
}

function stop(silent) {
  closeWebsocket(silent);
  stopInventory(silent);
}

// RFID模块的重置
async function reset() {
  // 关掉旧的连接
  stop(true);
  // 获取用户设备列表
  await getDeviceList();
}

async function getDeviceList() {
  const l = await api.list();
  if (l.length > 0) {
    l[0].selected = true;
  }
  deviceList.value = l;
  return deviceList;
}

// 定义外部可以使用的属性或方法
defineExpose({
  reset
})
</script>

<template>
  <div style="padding: 10px">
    <title-label>用户设备</title-label>
    <ul>
      <li v-for="d in deviceList">
        <div class="device-list">
          <div class="content">
            <span class="breath-light" :class="{'active': d.running}"></span>
            {{ d.name }}
          </div>
          <div>
            <el-button v-if="!d.running" size="small" @click="deviceRead(d)">读取</el-button>
            <el-button v-else size="small" @click="deviceStopRead(d)">停止</el-button>
          </div>
        </div>
      </li>
    </ul>

    <title-label>RFID标签</title-label>
    <ul>
      <li v-for="rfid in rfidList">{{rfid}}</li>
    </ul>
  </div>
</template>

<style scoped lang="scss">
  .device-list {
    display: flex;
    width: 100%;
    .content {
      flex-grow: 1;
    }
    .buttons {
      flex-shrink: 0;
    }
  }
</style>